/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  Dimensions,
  TouchableOpacity,
  Image,
  AsyncStorage,
  Alert,
  ScrollView
} from 'react-native';

import Toast from 'react-native-easy-toast' 
import Toaster, { ToastStyles } from 'react-native-toaster'

import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scrollview'

import styles1 from './styles/Pager.style';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import { Hoshi,Kohana,Makiko,Hideo,Akira,Fumi} from 'react-native-textinput-effects';
import { Bubbles, DoubleBounce, Bars, Pulse } from 'react-native-loader';

import DropdownAlert from 'react-native-dropdownalert'

var _navigator;

var net = require("./net/NetUitl");
var top = (Dimensions.get('window').height-200)/2-190;
class Login extends Component { 
	constructor(props) {  
		super(props);
		_navigator = this.props.navigator;
		this.state={
			username:"",
			password:"",
			message: null,
			flag:false,
		}
		
		this._login = this._login.bind(this);
		this._netCallBack = this._netCallBack.bind(this);
  	}
	
	componentDidMount() {
		_this = this;
		AsyncStorage.getItem("warning",function(errors,result){
			console.log(result);
			if(result == null){
				_this.setState({message:{ text: '由于服务器升级原因，老用户请重新修改下密码，带来不便请多谅解',
				styles: ToastStyles.warning,duration:8000}});
				//Alert.alert("由于服务器升级原因，老用户请重新修改下密码，带来不便请多谅解");
			}
		}); 
	}
		
	_netCallBack(data){
		console.log(data);
		if(data.code === "1"){
			this.refs.toast.show('登录成功');
			
			AsyncStorage.setItem('token',data.token,function(errs){
                //TODO:错误处理
                if (errs) {
                  console.log('存储错误');
                }
                if (!errs) {
                  console.log('存储无误');
                }
            });
            
            AsyncStorage.setItem('user_id',data.user_id,function(errs){
                //TODO:错误处理
                if (errs) {
                  console.log('存储错误');
                }
                if (!errs) {
                  console.log('存储无误');
                }
            });
            
            AsyncStorage.setItem('warning',"1",function(errs){
                //TODO:错误处理
                if (errs) {
                  console.log('存储错误');
                }
                if (!errs) {
                  console.log('存储无误');
                }
            });
            
            setTimeout(()=>{
				_navigator.resetTo({id:'first'});
			},1000);
		}else{
			this.dropdown.alertWithType('warn', '提醒', '密码错误或者用户名未注册');
//			_this.setState({message:{ text: '密码错误或者用户名未注册',
//				styles: ToastStyles.warning,duration:3000}});
			this.setState({flag:false});
		}  
	}
	
	_errorCallBack(){
		this.setState({flag:false});
	}
	
	toQueryString(obj) {
		    return obj ? Object.keys(obj).sort().map(function (key) {
		        var val = obj[key];
		        if (Array.isArray(val)) {
		            return val.sort().map(function (val2) {
		                return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
		            }).join('&');
		        }
		
		        return encodeURIComponent(key) + '=' + encodeURIComponent(val);
		    }).join('&') : '';
		}
	
	_login(){
		if(this.state.flag)
			return;
		
		this.setState({flag:true});
		
		console.log(this.state.username +"  "+ this.state.password); 
		
		let formData = new FormData();  
		formData.append("phonenumber",this.state.username);  
		formData.append("password",this.state.password);
		var fetchOptions = {
          	method: 'POST',
          	headers: { 
          		'Accept': 'application/json',
          	},
          	body: formData
       	}; 
        
		net.postFrom("http://www.idolly.com/user/index/login"
				,fetchOptions
				,this._netCallBack
				,this._errorCallBack);

//		var fetchOptions = {
//        method: 'POST',
//        body: {'phonenumber':"15608316520",'password':'123'}
//     	}; 
//
//	    fetch("http://192.168.1.125/idolly1/index.php/user/index/login", fetchOptions)
//	        .then((response) => response.json())
//	        .then((responseText) => {
//	          	console.log(responseText);
//      }).catch((error)=>{
//      	Alert.alert("error")
//      }).done();\

//		let formData = new FormData();  
//		formData.append("phonenumber","15608316520");  
//		formData.append("password","123");
//		var fetchOptions = {
//        method: 'POST',
//        headers: {     
//        },
//        body: formData
//     	}; 
//
//    	fetch("http://192.168.1.125/idolly1/index.php/user/index/login", fetchOptions)
//      	.then((response) => response.text())
//      	.then((responseText) => {
//        		Alert.alert(responseText);
//      	}).catch((error)=>{
//      			Alert.alert("error");
//      	}).done();
	} 
	
	scrollViewTo(){
　　　　let target = e.nativeEvent.target;
　　　　let scrollLength = 100;
　　　　if (target=== React.findNodeHandle(this.refs.codeInput)) {
　　　　　　scrollLength = 160;
　　　　}
　　　　this.refs.scroll.scrollTo(scrollLength);
　　}
	
	_HiddenBtn(){
		if(!this.state.flag){
			return(<Text style={{fontSize:20,color:"#6c1ddc"}}>登录</Text>);
		}else{
			return(<Bars size={10} color="#6c1ddc"/>);
		}
	}
	
	onClose(data) {
	  // data = {type, title, message}
	}
	
	render() {
	    return (
	      	<View style={styles1.container}>
		      	<KeyboardAwareScrollView style={{flex:1}} getTextInputRefs={() => { return [this._textInputRef];}}>	      			      				      	
		      		<View style={{flex:1}}>
		      		<View>
			      	<View style={[styles.header,{flex:1}]}>
		      			<Text style={{fontSize:40,color:'#ffffff'}}>科技改变生活</Text>
		      		</View>
		      		<View style={{width:Dimensions.get('window').width,height:100,backgroundColor: '#FAF4FF',}}/>
		      		<View style={styles.border}>
		      			<Image source={require("./image/common/logo.png")} style={styles.icon}/> 
		      		</View>
		      		</View>
		      		<View style={{flex:2, alignItems: 'center'}}> 			
			      		<View style={{width:Dimensions.get('window').width-40,marginTop:20}}>
			      			<View style={{flexDirection:'row',}} >
				      			<View style={{flex:1}}>
									<Fumi
										style={styles.textiput}
									    label={'请输入手机号'}
									    iconClass={FontAwesomeIcon}
									    iconName={'phone'} 
									    iconColor={'#f4d29a'}
									    inputStyle={{ color: '#91627b' }}
									    borderColor={'#a5d1cc'}
		   								labelStyle={{ color: '#6c1ddc' }}
									    value={this.state.username}
									    onChangeText={(text) => this.setState({username:text})}
				        				ref={(r) => { this._textInputRef = r; }}
									/> 
									<View style={{height:2,width:Dimensions.get('window').width}}/>
									<Fumi
										style={styles.textiput}
										secureTextEntry={true} 
									    label={'密码'}
									    iconClass={FontAwesomeIcon}
									    iconName={'lock'}
									    borderColor={'#a5d1cc'}
		   								labelStyle={{ color: '#6c1ddc' }}
									    inputStyle={{ color: '#91627b' }}
									    value={this.state.password}
				                       	onChangeText={(text) => this.setState({password:text})}
				        				ref={(r) => { this._textInputRef = r; }}
									/>
					      		</View>
					      		<TouchableOpacity onPress={this._login}>
					      			<View style={styles.login}>
					      				{this._HiddenBtn()}
					      			</View>
					      		</TouchableOpacity>
				      		</View> 
				      		<View style={{alignItems: 'center',flexDirection:'row'}}>
				      			<TouchableOpacity onPress={()=>{_navigator.push({id:"Register"})}}>
				      				<View style={{flexDirection:'row',justifyContent: 'center',height:20,marginTop:10}}>
					      				<FontAwesomeIcon name="user-plus" color={"#6c1ddc"} size={18}/>
					      				<Text style={{color:"#6c1ddc"}}> 注册新用户</Text>
					      			</View>
					      		</TouchableOpacity>
					      		<View style={{flex:1}}></View>
					      		<TouchableOpacity onPress={()=>{_navigator.push({id:"FixPassword"})}}>
				      				<View style={{flexDirection:'row',justifyContent: 'center',height:20,marginTop:10}}>
					      				<FontAwesomeIcon name="question-circle" color={"#6c1ddc"} size={18}/>
					      				<Text style={{color:"#6c1ddc"}}> 忘记密码</Text>
					      			</View>
					      		</TouchableOpacity>
				      		</View>
			      		</View>
			      	</View>
		      	 	</View>
	      	 	</KeyboardAwareScrollView>
	      	 	<Toast ref="toast"/>
		      	<Toaster message={this.state.message} onShow={()=>this.setState({message:null})}/>
		      	<DropdownAlert ref={(ref) => this.dropdown = ref} onClose={(data) => this.onClose(data)} />
	      	</View> 
	    );
	}
}

const styles = StyleSheet.create({
	container: {
	    flex: 1,
	    alignItems: 'center',
	    backgroundColor: '#f7f7f7',
	},
	login:{
		width:80,
		height:140,
		marginLeft:5,
	    justifyContent: 'center',
	    alignItems: 'center',
	    backgroundColor:'white',
		borderWidth:1,
		borderColor: '#6c1ddc',
	},
	bottom:{
		width:Dimensions.get('window').width,
		flexDirection:'row',
		backgroundColor: '#6c1ddc',
		alignItems: 'center',
		justifyContent: 'center',
		height:30,
	},
	textiput:{
		flex:1,
		borderWidth:1,
		borderColor: '#6c1ddc',
	},
	background:{
		position:"absolute",
		width:Dimensions.get('window').width,
		height:Dimensions.get('window').height
	},
	header:{
		height:Dimensions.get('window').height/2-100,
		width:Dimensions.get('window').width,
		justifyContent: 'center',
	    alignItems: 'center',
		backgroundColor: '#6c1ddc',
	},
	InnerheaderContent:{ 
		height:200,
		width:Dimensions.get('window').width,
		backgroundColor: '#6c1ddc',
	},
	border:{
		position:"absolute", 
		width:100,
		height:100,
		borderRadius:50,
		top:Dimensions.get('window').height/2-150,  
		left:Dimensions.get('window').width/2-50,
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: 'white',
		borderWidth:1
	},
	icon:{
		width:100,
		height:100, 
		marginLeft:4,
		marginTop:5,
	}
});

module.exports = Login;
